package com.zh.freechat.openfegin;

import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author Zhou
 * @date 16:24 2025/4/21
 */
@Slf4j
public class ChatServiceStarter {
    private Server server;

    public void start(int port, BindableService ... services) throws IOException, InterruptedException {
        ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
        for (var service : services) {
            serverBuilder.addService(service);
        }
        server = serverBuilder.build();
        server.start();

        log.info("*** gRPC server started success. listening on port {}",port);

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.warn("*** shutting down gRPC server since JVM is shutting down");
            try {
                server.shutdown().awaitTermination(30, java.util.concurrent.TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                log.warn("Interrupted.  {}",e.getMessage());
                e.printStackTrace(System.err);
            }
            log.info("*** server shut down");
        }));

//        server.awaitTermination(); //等待应用关闭
    }
}
